<!-- 申报类---预览、填报 -->
<template>
  <div>
    <Form :model="createForm" ref="approvalForm" :rules="ruleValidate" :label-width="100" :disabled="disable">
      <Row :gutter="10">
        <Col span="10">
          <Form-item prop="name" label="表单名称" :label-width="100">
            <Input type="text" v-model="createForm.name" placeholder="请输入表单名称"></Input>
          </Form-item>
        </Col>
        <Col span="12">
          <Form-item prop="menu" label="所属菜单" :label-width="150">
            <Cascader
              v-model="createForm.menu"
              @on-change="onChange"
              :data="options"
              :render-format="format"
              transfer
              :clearable="false"
            >
            </Cascader>
          </Form-item>
        </Col>
      </Row>
      <Row :gutter="10">
        <Col span="10">
          <Form-item prop="year" label="年份" :label-width="100">
            <DatePicker
              type="year"
              :value="defaultYear"
              @on-change="handleYearChange"
              transfer
              :clearable="false"
            ></DatePicker>
          </Form-item>
        </Col>
        <Col span="12">
          <Form-item prop="type" label="选择模板" :label-width="150">
            <Select size="default" v-model="createForm.type">
              <Option v-for="item in moduleOptions" :value="item.key" :key="item.key">{{ item.name }}</Option>
            </Select>
          </Form-item>
        </Col>
      </Row>
      <Row :gutter="10">
        <Col span="10" v-if="createForm.type === 2">
          <Form-item prop="subType" label="类型" :label-width="100">
            <div slot="label">
              类型
              <Tooltip
                transfer
                max-width="600"
                content="请根据实际情况填写细分申报类型，比如标杆项目、标杆个人等，若无细分类型，则无需填写"
                placement="right"
              >
                <Icon type="ios-help-circle-outline" />
              </Tooltip>
            </div>
            <Input v-model="createForm.subType" placeholder="请输入"></Input>
          </Form-item>
        </Col>
      </Row>
      <Row :gutter="10">
        <Col span="22">
          <Form-item prop="remark" label="备注" :label-width="100">
            <Input type="textarea" maxlength="300" :rows="4" v-model="createForm.remark" placeholder="请输入"></Input>
          </Form-item>
        </Col>
      </Row>
    </Form>
  </div>
</template>

<script>
import formCenterApi from '@/api/formCenter.js'
import { formType, STATUS_TYPE_DRAFT, STATUS_TYPE_PENDING } from '@/views/formConst'
import { findNodePath } from '@/views/menuList/menus'
import _ from 'lodash'
import { mapState } from 'vuex'
import { uuid } from 'vue-uuid'

export default {
  props: {
    row: {
      type: Object,
      default: () => {}
    },
    isCopy: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    ...mapState(['menuList']),
    disable() {
      if (this.isCopy) {
        return false
      } else {
        return this.row && ![STATUS_TYPE_DRAFT, STATUS_TYPE_PENDING].includes(this.row.status)
      }
    }
  },
  data() {
    return {
      loading: false,
      defaultYear: '2024',
      createForm: {
        name: '',
        menu: null,
        year: 2024,
        type: null,
        subType: '',
        remark: ''
      },
      moduleOptions: formType.filter(item => item.noOnline == false),
      ruleValidate: {
        name: [{ required: true, message: '请输入表单名称', trigger: 'blur' }],
        menu: [{ required: true, type: 'array', message: '请选择所属菜单', trigger: 'change' }],
        year: [{ required: true, type: 'date', message: '请选择年份', trigger: 'change' }],
        type: [{ required: true, type: 'number', message: '请选择模板类型', trigger: 'change' }]
      },
      options: []
    }
  },
  created() {
    this.onOk = _.debounce(this.onOk, 500)
    this.$emit('SetTitle', this.row ? '编辑表单' : '新增表单')
    this.$emit('SetPageWidth', 1000)
    this.$emit('SetPageMinHeight', 300)
    this.$emit('SetPageActions', [
      {
        text: '取消',
        handle: () => {
          this.$emit('Close')
        }
      },
      {
        text: '确定',
        theme: 'primary',
        loading: this.loading,
        disabled: this.disable,
        handle: () => {
          this.onOk()
        }
      }
    ])
    this.options = this.removeNodesWithToProperty(this.menuList)
    if (this.row) {
      this.createForm = JSON.parse(JSON.stringify(this.row))
      this.defaultYear = this.createForm.year + ''
      this.createForm.menu = findNodePath(this.options, this.createForm.menu)
    }
  },
  methods: {
    removeNodesWithToProperty(json) {
      // 递归函数，用于处理每个节点
      function processNode(node) {
        if (node.children && Array.isArray(node.children)) {
          // 过滤掉包含 to 属性的子节点
          node.children = node.children.filter(child => !child.to && !child.native)

          // 对剩余的子节点递归调用此函数
          node.children.forEach(processNode)
        }
      }

      // 创建 json 的深拷贝，以避免修改原始数据
      const result = JSON.parse(JSON.stringify(json))

      // 开始处理根节点
      result.forEach(rootNode => {
        processNode(rootNode)
      })

      return result
    },
    format(labels) {
      const index = labels.length - 1
      return labels[index]
    },
    onChange(value) {
      this.createForm.menu = value
    },
    handleYearChange(date) {
      this.defaultYear = date
      this.createForm.year = parseInt(date)
    },
    onOk() {
      this.$refs['approvalForm'].validate(valid => {
        if (valid) {
          const menu = [...this.createForm.menu].pop()
          if (!this.createForm.id) {
            this.loading = true
            formCenterApi
              .formInsert({ ...this.createForm, menu })
              .then(res => {
                if (res.data.code === 200) {
                  this.$Message.success({
                    content: '新建成功',
                    duration: 3
                  })
                  this.$emit('Close', this.createForm)
                }
              })
              .catch(() => {
                this.loading = false
              })
          } else {
            this.loading = true
            if (this.isCopy) {
              this.createForm.formId = this.createForm.id
              // 跨表单复制createForm里面的config的treeData得修改
              let config = JSON.parse(this.createForm.config)
              config.treeData[0].label = this.createForm.name
              if (this.row.type === this.createForm.type) {
                //同类型的修改标题
                const formDesc = config.treeData[0].formDesc
                if (formDesc && formDesc.length > 0) {
                  formDesc[0].default = this.createForm.name
                }
              } else {
                if (this.row.type === 2 && this.createForm.type === 3) {
                  // 申报类转评分类
                  config.treeData[0].weight = 100
                  delete config.treeData[0].formDesc
                }
                if (this.row.type === 3 && this.createForm.type === 2) {
                  // 评分类转申报类
                  delete config.treeData[0].weight
                  config.treeData[0].formDesc = [
                    {
                      id: uuid.v1(),
                      type: 'text',
                      break: true,
                      class: 'title',
                      label: '',
                      layout: 23,
                      default: this.createForm.name,
                      maxlength: 300,
                      labelWidth: '0'
                    }
                  ]
                }
              }
              this.createForm.config = JSON.stringify(config)
              console.log(JSON.stringify(this.createForm))
              formCenterApi
                .formCopy({ ...this.createForm, menu })
                .then(res => {
                  if (res.data.code === 200) {
                    this.$Message.success({
                      content: '复制成功',
                      duration: 3
                    })
                    this.$emit('Close', this.createForm)
                  }
                })
                .catch(() => {
                  this.loading = false
                })
            } else {
              formCenterApi
                .formUpdate({ ...this.createForm, menu })
                .then(res => {
                  if (res.data.code === 200) {
                    this.$Message.success({
                      content: '修改成功',
                      duration: 3
                    })
                    this.$emit('Close', this.createForm)
                  }
                })
                .catch(() => {
                  this.loading = false
                })
            }
          }
        }
      })
    }
  }
}
</script>

<style lang="less" scoped></style>
